import {BadRequestException, Body, Controller, Delete, Get, Param, Post, Put} from '@nestjs/common';
import {UserService} from "./user.service";
import {UserDto} from "./dto/user.dto";
import {CreateUserDto} from "./dto/create-user.dto";

@Controller('user')
export class UserController {

    constructor(private readonly userService: UserService) {
    };

    @Get()
    async findAll() {
        return await this.userService.findAll();
    }

    @Get(':id')
    async findById(@Param('id') id: string) {
        return await this.userService.findById(+id);
    }

    @Post()
    async create(@Body() body: Omit<UserDto, 'id'>) {
        return await this.userService.create(body);
    }

    @Put(":id")
    async update(@Param('id') id: string, @Body() body: Partial<UserDto>) {
        return await this.userService.update(+id, body);
    }

    @Delete(':id')
    async remove(@Param('id') id: string) {
        const success = await this.userService.remove(+id);
        return {success};
    }

    @Post('batch')
    async createMany(@Body() users: CreateUserDto[]) {
        if (!Array.isArray(users)) {
            throw new BadRequestException('请求体必须是一个用户数组');
        }

        const createUsers = await this.userService.createMany(users);
        return {
            message: `成功添加 ${createUsers.length} 个用户`,
            data: createUsers,
        };
    }
}
